package cn.pfz.realm;

import cn.pfz.Service.IEmployeeSerives;
import cn.pfz.Service.IPermissionSerives;
import cn.pfz.Service.IRoleSerives;
import cn.pfz.domain.Employee;

import cn.pfz.domain.Role;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IRoleSerives roleSerives;
    @Autowired
    private IEmployeeSerives employeeSerives;
    @Autowired
    private IPermissionSerives permissionSerives;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取主题对象
        Employee emp = (Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (emp.isAdmin()){
            info.addRole("admin");
            //根据权限表达式写
            info.addStringPermission("*:*");
            return info;
        }
        //获取当前的用户角色
        List<String> roleList = roleSerives.selectRoleByEmployeeId(emp.getId());

        //获取当前用户的权限
        List<String> perList  =    permissionSerives.getPermissionExperssionByEmployeeId(emp.getId());
        //给当前用户授权
info.addRoles(roleList);
info.addStringPermissions(perList);
return info;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken =(UsernamePasswordToken) authenticationToken;
        Employee employee = employeeSerives.selectByUsername(usernamePasswordToken.getUsername());
if(employee==null){
    return null;
}else {
    //认证成功后得到employee对象（第一个参数）
    AuthenticationInfo info = new SimpleAuthenticationInfo(employee,
            employee.getPassword(),
            ByteSource.Util.bytes(employee.getName()),
            this.getName());
    return info;
}


    }
    
    //获取用户的密钥，盐 创建含有密钥的对象  进行登录验证
    @Override
    @Autowired
    public void  setCredentialsMatcher(CredentialsMatcher credentialsMatcher){
super.setCredentialsMatcher(credentialsMatcher);
    }

}
